<?php

function ismobile($agent)
{
    $ismobile=0;
    $mobile = [ "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" ];
    foreach($mobile as $k)
    {
        if(strstr(strtolower($agent),strtolower($k)))
        {
            $ismobile=1;
            break;
        }
    }
    return $ismobile;
}

function checkingroup($groupname) {
    $CI    =& get_instance();
    $CI->load->library(['ion_auth']);
    return $CI->ion_auth->in_group($groupname);   
}


function sortarray($data,$sortkey)
{
    $sort=[];
    foreach ($data as $key => $row) {
        $sort[$key] = $row[$sortkey];
    }
    array_multisort($sort, SORT_DESC, $data);
    return $data;
}

function mkdirs($path) {
    if (!is_dir($path)) {
        mkdirs(dirname($path));
        mkdir($path);
    }
    return is_dir($path);
}

function strexists($string, $find) {
    return !(strpos($string, $find) === FALSE);
}

function friendlyDatemore($sTime) {
    if (!$sTime)
        return '';
    $cTime      =   time();
    $dTime      =   $sTime - $cTime;
   
    $datetime1 = new DateTime(date("Y-m-d"));
    $datetime2 = new DateTime(date("Y-m-d",$sTime));
    $interval = $datetime1->diff($datetime2);
    $dDay=$interval->format('%a');
    $g=$interval->format('%R');
    if($g=="-" && $dDay>0)
    {
        return '已过期 '.date("m-d H:i",$sTime);
    }elseif($dDay == 0){
        //return intval($dTime/3600)."小时前";
        return '今天'.date('H:i',$sTime);
    }elseif($dDay==1){
        return "明天";
    }elseif($dDay==2){
        return "后天";
    }else{
        return $dDay."天后";
    }
    
}

function num2alpha($intNum, $isLower = false)
{
    $num26 = base_convert($intNum, 10, 26);
    $addcode = $isLower ? 49 : 17;
    $result = '';
    for ($i = 0; $i < strlen($num26); $i++) {
        $code = ord($num26{$i});
        if ($code < 58) {
            $result .= chr($code + $addcode);
        } else {
            $result .= chr($code + $addcode - 39);
        }
    }
    return $result;
}


function iajax($code = 0, $message = '', $redirect = '') {
    message(error($code, $message), $redirect, 'ajax', false);
}

function pagination($total, $pageIndex, $pageSize = 15, $url = '', $context = array('before' => 5, 'after' => 4, 'ajaxcallback' => '', 'callbackfuncname' => '')) {
    $_W["scriptname"]=scriptname();
    $pdata = array(
        'tcount' => 0,
        'tpage' => 0,
        'cindex' => 0,
        'findex' => 0,
        'pindex' => 0,
        'nindex' => 0,
        'lindex' => 0,
        'options' => ''
    );
    if ($context['ajaxcallback']) {
        $context['isajax'] = true;
    }
    
    if (isset($context['callbackfuncname']) && $context['callbackfuncname']) {
        $callbackfunc = $context['callbackfuncname'];
    }
    
    $pdata['tcount'] = $total;
    $pdata['tpage'] = (empty($pageSize) || $pageSize < 0) ? 1 : ceil($total / $pageSize);
    if ($pdata['tpage'] <= 1) {
        return '';
    }
    $cindex = $pageIndex;
    $cindex = min($cindex, $pdata['tpage']);
    $cindex = max($cindex, 1);
    $pdata['cindex'] = $cindex;
    $pdata['findex'] = 1;
    $pdata['pindex'] = $cindex > 1 ? $cindex - 1 : 1;
    $pdata['nindex'] = $cindex < $pdata['tpage'] ? $cindex + 1 : $pdata['tpage'];
    $pdata['lindex'] = $pdata['tpage'];

    if ($context['isajax']) {
        if (empty($url)) {
            $url = $_W['script_name'] . '?' . http_build_query($_GET);
        }
        $pdata['faa'] = 'href="javascript:;" page="' . $pdata['findex'] . '" '. ($callbackfunc ? 'onclick="'.$callbackfunc.'(\'' . $url . '\', \'' . $pdata['findex'] . '\', this);return false;"' : '');
        $pdata['paa'] = 'href="javascript:;" page="' . $pdata['pindex'] . '" '. ($callbackfunc ? 'onclick="'.$callbackfunc.'(\'' . $url . '\', \'' . $pdata['pindex'] . '\', this);return false;"' : '');
        $pdata['naa'] = 'href="javascript:;" page="' . $pdata['nindex'] . '" '. ($callbackfunc ? 'onclick="'.$callbackfunc.'(\'' . $url . '\', \'' . $pdata['nindex'] . '\', this);return false;"' : '');
        $pdata['laa'] = 'href="javascript:;" page="' . $pdata['lindex'] . '" '. ($callbackfunc ? 'onclick="'.$callbackfunc.'(\'' . $url . '\', \'' . $pdata['lindex'] . '\', this);return false;"' : '');
    } else {
        if ($url) {
            $pdata['faa'] = 'href="?' . str_replace('*', $pdata['findex'], $url) . '"';
            $pdata['paa'] = 'href="?' . str_replace('*', $pdata['pindex'], $url) . '"';
            $pdata['naa'] = 'href="?' . str_replace('*', $pdata['nindex'], $url) . '"';
            $pdata['laa'] = 'href="?' . str_replace('*', $pdata['lindex'], $url) . '"';
        } else {
            $_GET['page'] = $pdata['findex'];
            $pdata['faa'] = 'href="' . $_W['script_name'] . '?' . http_build_query($_GET) . '"';
            $_GET['page'] = $pdata['pindex'];
            $pdata['paa'] = 'href="' . $_W['script_name'] . '?' . http_build_query($_GET) . '"';
            $_GET['page'] = $pdata['nindex'];
            $pdata['naa'] = 'href="' . $_W['script_name'] . '?' . http_build_query($_GET) . '"';
            $_GET['page'] = $pdata['lindex'];
            $pdata['laa'] = 'href="' . $_W['script_name'] . '?' . http_build_query($_GET) . '"';
        }
    }

    $html = '<div><ul class="pagination pagination-centered">';
    if ($pdata['cindex'] > 1) {
        $html .= "<li><a {$pdata['faa']} class=\"pager-nav\">首页</a></li>";
        $html .= "<li><a {$pdata['paa']} class=\"pager-nav\">&laquo;上一页</a></li>";
    }
        if (!$context['before'] && $context['before'] != 0) {
        $context['before'] = 5;
    }
    if (!$context['after'] && $context['after'] != 0) {
        $context['after'] = 4;
    }

    if ($context['after'] != 0 && $context['before'] != 0) {
        $range = array();
        $range['start'] = max(1, $pdata['cindex'] - $context['before']);
        $range['end'] = min($pdata['tpage'], $pdata['cindex'] + $context['after']);
        if ($range['end'] - $range['start'] < $context['before'] + $context['after']) {
            $range['end'] = min($pdata['tpage'], $range['start'] + $context['before'] + $context['after']);
            $range['start'] = max(1, $range['end'] - $context['before'] - $context['after']);
        }
        for ($i = $range['start']; $i <= $range['end']; $i++) {
            if ($context['isajax']) {
                $aa = 'href="javascript:;" page="' . $i . '" '. ($callbackfunc ? 'onclick="'.$callbackfunc.'(\'' . $url . '\', \'' . $i . '\', this);return false;"' : '');
            } else {
                if ($url) {
                    $aa = 'href="?' . str_replace('*', $i, $url) . '"';
                } else {
                    $_GET['page'] = $i;
                    $aa = 'href="?' . http_build_query($_GET) . '"';
                }
            }
            $html .= ($i == $pdata['cindex'] ? '<li class="active"><a href="javascript:;">' . $i . '</a></li>' : "<li><a {$aa}>" . $i . '</a></li>');
        }
    }

    if ($pdata['cindex'] < $pdata['tpage']) {
        $html .= "<li><a {$pdata['naa']} class=\"pager-nav\">下一页&raquo;</a></li>";
        $html .= "<li><a {$pdata['laa']} class=\"pager-nav\">尾页</a></li>";
    }
    $html .= '</ul></div>';
    return $html;
}


function scriptname() {
    $_W=array();
    $_W['script_name'] = basename($_SERVER['SCRIPT_FILENAME']);
    if(basename($_SERVER['SCRIPT_NAME']) === $_W['script_name']) {
        $_W['script_name'] = $_SERVER['SCRIPT_NAME'];
    } else {
        if(basename($_SERVER['PHP_SELF']) === $_W['script_name']) {
            $_W['script_name'] = $_SERVER['PHP_SELF'];
        } else {
            if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $_W['script_name']) {
                $_W['script_name'] = $_SERVER['ORIG_SCRIPT_NAME'];
            } else {
                if(($pos = strpos($_SERVER['PHP_SELF'], '/' . $scriptName)) !== false) {
                    $_W['script_name'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $_W['script_name'];
                } else {
                    if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'], $_SERVER['DOCUMENT_ROOT']) === 0) {
                        $_W['script_name'] = str_replace('\\', '/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $_SERVER['SCRIPT_FILENAME']));
                    } else {
                        $_W['script_name'] = 'unknown';
                    }
                }
            }
        }
    }
    return $_W['script_name'];
}

function error($errno, $message = '') {
    return array(
        'errno' => $errno,
        'message' => $message,
    );
}


function dd($var)
{
    if(is_array($var))
    {
        print_r($var);
    } else if(is_object($var))
    {
        var_dump($var);
    } else {
        echo $var;
    }
    die();
}

if ( ! function_exists('getadminshow'))
{

    function getadminshow($id){
       $CI    =& get_instance();
       $CI->load->model('user_model');
       return $CI->user_model->get_admin_name($id);
    }

}


if ( ! function_exists('get_system_settings'))
{
    function get_system_settings() {
        
        $CI    =& get_instance();
        $CI->load->model('systemconfig_model');
        return $CI->systemconfig_model->getsysconfig();   
    }
}

function getpropriceeditlink($site,$proname)
{
    if($site["sitetype"]==2)
    {
        $extra=json_decode($site["extra"],true);
        $link="https://".$extra["apihost"]."/admin/bulk?resource_name=Product&app_context=&edit=variants.sku%2Cvariants.price%2Cvariants.compare_at_price&show=&return_to=%2Fadmin%2Fproducts&metafield_titles=&metafield_options=&query=".urlencode($proname)."&order=title+asc";
        return $link;
    }
    else
    {
        return "#";
    }
}

function getproeditlink($site,$rid)
{
    $link="";
    switch($site["sitetype"])
    {
        case 1:
            $link=$site["domian"].'/wp-admin/post.php?post='.$rid.'&action=edit';
            break;
        case 2:
            $extra=json_decode($site["extra"],true);
            $link="https://".$extra["apihost"]."/admin/products/".$rid;
            break;
    }
    return $link;
}


function loadsystemlink($site)
{
    $CI =& get_instance();
    switch($site["sitetype"])
	{
        case 1:
            $adminlink=$site["domian"].'?_dreamtoken='.$site["apipass"];
            $CI->load->library('sitetype/wordpress',$site,'mysite');
            break;
 
    }
    return $adminlink;
}

function getconfig($name)
{
    $config=get_system_settings();
    return $config[$name];
}


if ( ! function_exists('tpl_form_field_multi_image'))
{

function tpl_form_field_multi_image($name, $value = array(), $options = array()) {

    $options['multiple'] = true;
    $options['direct'] = false;
    $options['fileSizeLimit'] = 6 * 1024 * 1024;

    if (isset($options['dest_dir']) && !empty($options['dest_dir'])) {
        if (!preg_match('/^\w+([\/]\w+)?$/i', $options['dest_dir'])) {
            exit('图片上传目录错误,只能指定最多两级目录,如: "we7_store","we7_store/d1"');
        }
    }
    $s = '';
    if (!defined('TPL_INIT_MULTI_IMAGE')) {
        $s = '
<script type="text/javascript">
    function uploadMultiImage(elm) {
        var name = $(elm).next().val();
        util.image( "", function(urls){
            $.each(urls, function(idx, url){
                $(elm).parent().parent().next().prepend(\'<div class="multi-item"><img onerror="this.src=\\\'./resource/images/nopic.jpg\\\'; this.title=\\\'图片未找到.\\\'" src="\'+url.url+\'" class="img-responsive img-thumbnail"><input type="hidden" name="\'+name+\'[]" value="\'+url.attachment+\'"><em class="close" title="删除这张图片" onclick="deleteMultiImage(this)">×</em></div>\');
            });
        }, ' . json_encode($options) . ');
    }
    function deleteMultiImage(elm){
        $(elm).parent().remove();
    }
</script>';
        define('TPL_INIT_MULTI_IMAGE', true);
    }

    $s .= <<<EOF
<div class="input-group">
    <input type="text" class="form-control" readonly="readonly" value="" placeholder="批量上传图片" autocomplete="off">
    <span class="input-group-btn">
        <button class="btn btn-default" type="button" onclick="uploadMultiImage(this);">选择图片</button>
        <input type="hidden" value="{$name}" />
    </span>
</div>
<div class="input-group multi-img-details">
EOF;
    if (is_array($value) && count($value) > 0) {
        foreach ($value as $row) {
            $s .= '
<div class="multi-item">
    <img src="' . tomedia($row) . '" onerror="this.src=\'./resource/images/nopic.jpg\'; this.title=\'图片未找到.\'" class="img-responsive img-thumbnail">
    <input type="hidden" name="' . $name . '[]" value="' . $row . '" >
    <em class="close" title="删除这张图片" onclick="deleteMultiImage(this)">×</em>
</div>';
        }
    }
    $s .= '</div>';

    return $s;
}

}
if ( ! function_exists('tomedia'))
{
    function tomedia($src, $local_path = false){
        //global $_W;
        if (empty($src)) {
            return '';
        }

        $t = strtolower($src);

        if ((substr($t, 0, 7) == 'http://') || (substr($t, 0, 8) == 'https://')) {
            return $src;
        }
        if(substr($t, 0, 2) == '//'){
            return "http:".$src;
        }

        $config = get_system_settings(); 

        $src = $config["urlpath"].'/'.$src;
        
        return $src;
    }
}

if ( ! function_exists('payorder'))
{
    function payorder($order)
    {
        $CI    =& get_instance();
        $CI->load->model(['siteproduct_model','siteuser_model','goods_model']);
        $order["productinfo"]=json_decode($order["productinfo"],true);   
        $sellcount=[];
        $sitesellcount=[];        
        foreach($order["productinfo"] as $p)
        {   
            $localres=$CI->siteproduct_model->getsitepro($order["siteid"],$p["rid"]);
            if($localres)
            {
                $sitesellcount[$localres["id"]]=$p["quantity"];
                $localproduct=$CI->goods_model->getbyid($localres["productid"]);
                if($localproduct)
                {
                    $sellcount[$localproduct["id"]]=$p["quantity"];
                }
            }
            
        }
        foreach($sellcount as $k=>$v)
        {
            $CI->goods_model->addsell($k,$v);
        }
        foreach($sitesellcount as $k=>$v)
        {
            $CI->siteproduct_model->addsell($k,$v);
        }
        $cuinfo=$CI->siteuser_model->get_item_by_where(["uid"=>$order["uid"]]);
        $newinfo=["ordercount"=>$cuinfo["ordercount"]+1,"totalamount"=>$cuinfo["totalamount"]+$order["amount"]];
        $CI->siteuser_model->update($cuinfo["id"],$newinfo);
    }
}


if ( ! function_exists('tpl_ueditor'))
{
    function tpl_ueditor($id, $value = '', $options = array()) {
        $s = '';
        if(!isset($options['dest_dir'])){
            $options['dest_dir']="";
        }
        $options['height'] = empty($options['height']) ? 200 : $options['height'];
        $options['allow_upload_video'] = isset($options['allow_upload_video']) ? $options['allow_upload_video'] : true;
        $s .= !empty($id) ? "<textarea id=\"{$id}\" name=\"{$id}\" type=\"text/plain\" style=\"height:{$options['height']}px;\">{$value}</textarea>" : '';
        $s .= "
		<script type=\"text/javascript\">
		$(function(){
            require(['util'], function(util){
                util.editor('" . ($id ? $id : "") . "', {
                height : {$options['height']}, 
                dest_dir : '" .($options['dest_dir'] ? $options['dest_dir'] : "") . "',
                image_limit : " . (6*1024 * 1024) . ",
                allow_upload_video : " . ($options['allow_upload_video'] ? 'true' : 'false') . ",
                audio_limit : " . (6*1024 * 1024) . ",
                callback : ''
                });
			});
		});
        </script>";
        return $s;
    }
}

function _tpl_form_field_date($name, $value = '', $withtime = false) {
	$s = '';
	$withtime = empty($withtime) ? false : true;
	if (!empty($value)) {
		$value = strexists($value, '-') ? strtotime($value) : $value;
        $value = ($withtime ? date('Y-m-d H:i:s', $value) : date('Y-m-d', $value));
    } else {
        //$value = time();
        $value = "";
	}
	$s .= '<input type="text" name="' . $name . '"  value="'.$value.'" placeholder="请选择日期时间" readonly="readonly" class="datetimepicker form-control" style="padding-left:12px;" />';
	$s .= '
		<script type="text/javascript">
			require(["datetimepicker"], function(){
					var option = {
						lang : "zh",
						step : 5,
						timepicker : ' . (!empty($withtime) ? "true" : "false") .',
						closeOnDateSelect : true,
						format : "Y-m-d' . (!empty($withtime) ? ' H:i"' : '"') .'
					};
				$(".datetimepicker[name = \'' . $name . '\']").datetimepicker(option);
			});
		</script>';
	return $s;
}




if ( ! function_exists('tpl_form_field_daterange'))
{
    function tpl_form_field_daterange($name, $value = array(), $time = false) {
        
        $s = '';
        if(!defined('TPL_INIT_DATERANGE_DATE')){
            echo '<link rel="stylesheet" type="text/css" media="all" href="/assets/frameworks/daterangepicker/daterangepicker.css" />';
            echo '<script type="text/javascript" src="/assets/frameworks/jquery/jquery.min.js"></script>';
            echo '<script type="text/javascript" src="/assets/frameworks/bootstrap/js/bootstrap.min.js"></script>';
            echo '<script type="text/javascript" src="/assets/frameworks/moment.js"></script>';
            echo '<script type="text/javascript" src="/assets/frameworks/daterangepicker/daterangepicker.js"></script>';
        }
        
        if (empty($time) && !defined('TPL_INIT_DATERANGE_DATE')) {
            
            $s = '
    <script type="text/javascript">
    	
    		$(document).ready(function(){
    			$(".daterange.daterange-date").each(function(){
    				var elm = this;
    				$(this).daterangepicker({
    					startDate: $(elm).prev().prev().val(),
    					endDate: $(elm).prev().val(),
    					format: "YYYY-MM-DD"
    				}, function(start, end){
    					$(elm).find(".date-title").html(start.toDateStr() + " 至 " + end.toDateStr());
    					$(elm).prev().prev().val(start.toDateStr());
    					$(elm).prev().val(end.toDateStr());
    				});
    			});
    		});
    	
    </script>
    ';
            define('TPL_INIT_DATERANGE_DATE', true);
        }
    
        if (!empty($time) && !defined('TPL_INIT_DATERANGE_TIME')) {
            $s = '
    <script type="text/javascript">
    	
    		$(document).ready(function(){
    			$(".daterange.daterange-time").each(function(){
    				var elm = this;
    				$(this).daterangepicker({
    					startDate: $(elm).prev().prev().val(),
    					endDate: $(elm).prev().val(),
    					format: "YYYY-MM-DD HH:mm",
    					timePicker: true,
    					timePicker12Hour : false,
    					timePickerIncrement: 1,
    					minuteStep: 1
    				}, function(start, end){
    					$(elm).find(".date-title").html(start.toDateTimeStr() + " 至 " + end.toDateTimeStr());
    					$(elm).prev().prev().val(start.toDateTimeStr());
    					$(elm).prev().val(end.toDateTimeStr());
    				});
    			});
    		});
    	
    </script>
    ';
            define('TPL_INIT_DATERANGE_TIME', true);
        }
    
        if(isset($value['start']) && $value['start']) {
            $value['starttime'] = empty($time) ? date('Y-m-d',strtotime($value['start'])) : date('Y-m-d H:i',strtotime($value['start']));
        }
        if(isset($value['end']) && $value['end']) {
            $value['endtime'] = empty($time) ? date('Y-m-d',strtotime($value['end'])) : date('Y-m-d H:i',strtotime($value['end']));
        }
        $value['starttime'] = empty($value['starttime']) ? (empty($time) ? date('Y-m-d') : date('Y-m-d H:i') ): $value['starttime'];
        $value['endtime'] = empty($value['endtime']) ? $value['starttime'] : $value['endtime'];
        $s .= '
    	<input name="'.$name . '[start]'.'" type="hidden" value="'. $value['starttime'].'" />
    	<input name="'.$name . '[end]'.'" type="hidden" value="'. $value['endtime'].'" />
    	<button class="btn btn-default daterange '.(!empty($time) ? 'daterange-time' : 'daterange-date').'" type="button"><span class="date-title">'.$value['starttime'].' 至 '.$value['endtime'].'</span> <i class="fa fa-calendar"></i></button>
    	';
        return $s;
    }

}




function get_price($ruler,$price)
{    
    $rulerarr=explode("||",$ruler);
    foreach($rulerarr as $ru)
    {
        if(!strstr($ru,":")){
            return execute_price($ru,$price);
        }else{
            $row=explode(":",$ru);
            if(strstr($row[0],"-"))
            {
                $qu=explode("-",$row[0]);
                if($price>=$qu[0] && $price<=$qu[1])
                {
                    return execute_price($row[1],$price);
                }
            }
            else
            {
                return execute_price($row[1],$price);
            }
        }
    }
    return $price;
}

function execute_price($gs,$price)
{
    if(strstr($gs,"#"))
    {
        $tmp=explode("#",$gs);
        if($tmp[0]=="plus")
        {
            $price = $price+$tmp[1];
        }
        else if($tmp[0]=="multi")
        {
            $price = $price*$tmp[1];
        }
        else if($tmp[0]=="formula")
        {
            eval("\$price={$tmp[1]};"); 
        }   
    }
    return sprintf("%.2f",$price);   
}

function ipv6toipv4($ip)
{
    $ipv4 = hexdec(substr($ip, 0, 2)) . "." . hexdec(substr($ip, 2, 2)) . "." . hexdec(substr($ip, 5, 2)) . "." . hexdec(substr($ip, 7, 2));
    return $ipv4;
}

function inquiry_source($source_url)
{
    if(strstr($source_url,'/contact'))
    {
        $source = 'contact';
    }elseif(strstr($source_url,'/products')){
        $source = 'products';
    }elseif (strstr($source_url,'/product-item')||strstr($source_url,'/portfolio-item')){
        $source = 'product-item';
    }elseif (strstr($source_url,'/services')){
        $source = 'FAQ';
    }elseif (strstr($source_url,'/about-us')){
        $source = 'about';
    }else{
        $source = 'Home';
    }
    return $source;
}
